package com.rongxue.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rongxue.mapper.*;
import com.rongxue.pojo.*;
import com.rongxue.service.ProjectService;
import com.rongxue.service.SareaService;
import com.rongxue.service.shanbei.services.AccountService;
import com.rongxue.service.shanbei.util.ConfigUtil;
import com.rongxue.service.utils.P2PMessageUtils;
import com.rongxue.service.utils.RecordsUtils;
import com.rongxue.utils.CommonUtils;
import com.rongxue.utils.DateUtil;

import com.rongxue.utils.Page;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


@Service
@Transactional
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private SProjectMapper projectMapper;
    @Autowired
    private SUserMapper userMapper;
    @Autowired
    private SUserBankMapper userBankMapper;
    @Autowired
    private SInvestmentDetailMapper investmentDetailMapper;
    @Autowired
    private SUserRedenvelopeMapper userRedenvelopeMapper;//红包
    @Autowired
    private SUserInterestCouponMapper userInterestCouponMapper;

    @Autowired
    private SUserAccountMapper userAccountMapper;

    @Autowired
    private RecordsUtils recordsUtils;

    @Autowired
    private  SUserDueDetailMapper sUserDueDetailMapper;

    @Autowired
    private SUserWalletRecordsMapper sUserWalletRecordsMapper;

    @Autowired
    private SRepaymentDetailMapper repaymentDetailMapper;

    //@Value("${MCHNT_CD}")
    public String MCHNT_CD = CashInAndOutServiceImpl.MCHNT_CD;//商户代码
    //@Value("${PAGE_NOTIFY_URL}")
    private String PAGE_NOTIFY_URL = CashInAndOutServiceImpl.PAGE_NOTIFY_URL;//商户回调地址
    //@Value("${P2P_SEND_MSG_URL}")
    private String P2P_SEND_MSG_URL = CashInAndOutServiceImpl.P2P_SEND_MSG_URL;//认证支付url
    //@Value("${KEY}")
    private String KEY = CashInAndOutServiceImpl.KEY;//密钥
    //@Value("${APP_MCHNT_CD}")
    public String APP_MCHNT_CD = CashInAndOutServiceImpl.APP_MCHNT_CD;//APP商户代码

    private static final Logger LOGGER = LoggerFactory.getLogger(ProjectService.class);


    //用户投资
    @Override
    public ObjectResult tender(XMLBean xmlBean) {
        String userId =CommonUtils.decToken(xmlBean.getToken());
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        SUser resultUser = userMapper.selectUserInfoById(Long.parseLong(userId));
        if (resultUser == null) {
            return ObjectResult.build("0", "用户信息错误,请重试");
        }

        //查询身份证是否被绑定
        if (resultUser.getCardNoAuth() == null || resultUser.getCardNoAuth() != 1) {
            return ObjectResult.build("0", "投资前请实名认证");
        }

        SUserBank sUserBank = userBankMapper.selectUserBankByUserId(userId);
        if (sUserBank == null) {
            return ObjectResult.build("0", "投资前请绑定银行卡");
        }

        //标验证
        SProject project = projectMapper.selectByPrimaryKey(Long.parseLong(xmlBean.getProject_id()));
        //SProject project =  projectMapper.selectProjectInfo(SInvestmentDetail.getProjectId());
        if (project == null) {
            return ObjectResult.build("0", "标信息错误,请重试");
        }
        BigDecimal ableMoney = project.getAble();
        //如果此标的可投金额为0
        if (ableMoney.compareTo(new BigDecimal(0.00)) <= 0) {
            return ObjectResult.build("0", "此标已满", new ArrayList());
        }
        //用户想要投资的金额
        BigDecimal amount = new BigDecimal(xmlBean.getAmoney());
        //用户使用红包后的真实金额，如果没有使用红包则真实金额和想要投资金额一样
        //BigDecimal realMoney = new BigDecimal(xmlBean.getMoney());
        //TODO X 真实金额就是投资金额，使用红包，在提取收益的时候，在reward_value加上红包金额
        BigDecimal realMoney = new BigDecimal(xmlBean.getMoney());
        //xmlBean.setMoney(amount.toString());
        //用户投资金额要大于此标最小投资金额 小于最大投资金额
        BigDecimal minMoney = new BigDecimal(project.getMoney_min());
        BigDecimal maxMoney = new BigDecimal(project.getMoney_max());
        //如果最大的可投金额是0则不限制
        if (0 != maxMoney.doubleValue()) {
            if (amount.compareTo(maxMoney) <= 0) {
                //如果用户投资金额大于此标可投金额 则用户所投投金额变成标可投金额
                if (amount.compareTo(ableMoney) > 0) {
                    return ObjectResult.build("0", "投资金额大于此标的可投金额");
                }
            } else {
                return ObjectResult.build("0", "金额大于最大投资金额");
            }
        }
        if (amount.compareTo(minMoney) >= 0) {
            //如果用户投资金额大于此标可投金额 则用户所投投金额变成标可投金额
            if (amount.compareTo(ableMoney) > 0) {
                return ObjectResult.build("0", "投资金额大于此标的可投金额");
            }
        } else {
            return ObjectResult.build("0", "金额小于此标的投资金额");
        }

        if (project.getNew_preferential() == 1 && resultUser.getLevel() != 1) {
            return ObjectResult.build("0", "您已经购买过，不能再投资新人特惠标！");
        }

        int awardType = 0;
        int awardId = 0;
        BigDecimal redAmount = new BigDecimal(0.00);
        BigDecimal couponInterestRate = new BigDecimal(0.00);
        //计算用户利息
        BigDecimal user_interest = project.getUser_interest();
        BigDecimal  dayInterest = user_interest.divide(BigDecimal.valueOf(360 * 100), 10, BigDecimal.ROUND_HALF_EVEN);//日息
        BigDecimal  rateCoupon =  dayInterest.multiply(amount).multiply(new BigDecimal(project.getDuration()));

        //给用户的利息
        BigDecimal  interest_new  = project.getUser_interest();


        //加息券红包验证
        if (xmlBean.getAward_id() != null && !xmlBean.getAward_id().equals("") && xmlBean.getAward_type() != null && !xmlBean.getAward_type().equals("")) {
            awardType = Integer.parseInt(xmlBean.getAward_type());
            LOGGER.info("awardType is " + awardType);
            awardId = Integer.parseInt(xmlBean.getAward_id());
            //红包或加息券验证
            if (awardType == 1) {
                // 验证红包相关信息,奖励类型:1红包,2现金券,加息券
                SUserRedenvelope userRed = userRedenvelopeMapper.selectByPrimaryKey(Integer.valueOf(xmlBean.getAward_id()));
                if (userRed == null || userRed.getStatus() != 0) {
                    return ObjectResult.build("0", "系统无法找到红包或红包失效！");
                }

                //最小投资金额验证
                if (amount.compareTo(userRed.getMinInvest()) < 0){
                    return ObjectResult.build("0", "投资金额未达到红包使用要求");
                }
                //最小投资天数验证
                if (project.getDuration() < userRed.getMinDue()){
                    return ObjectResult.build("0", "投资天数未达到红包使用要求");
                }

                if (amount.subtract(realMoney).compareTo(userRed.getAmount()) != 0) {
                    ObjectResult.build("0", "红包金额不匹配");
                }
                redAmount = userRed.getAmount();


            } else if (awardType == 2) {
                //验证加息券相关信息,奖励类型:1红包,2现金券,加息券
                SUserInterestCoupon coupon = userInterestCouponMapper.selectByPrimaryKey(Integer.valueOf(xmlBean.getAward_id()));

                // awardId = coupon.getId();
                if (coupon == null || coupon.getStatus() != 0) {
                    return ObjectResult.build("0", "系统无法找到加息券或券包失效!");
                }
                Double interestRate = coupon.getInterestRate().doubleValue();
                if (interestRate > 10 || interestRate <= 0) {
                    return ObjectResult.build("0", "加息券金额错误!");
                }

                //最小投资金额验证
                if (amount.compareTo(coupon.getMinInvest()) < 0){
                    return ObjectResult.build("0", "投资金额未达到加息券使用要求");
                }
                //最小投资天数验证
                if (project.getDuration() < coupon.getMinDue()){
                    return ObjectResult.build("0", "投资天数未达到加息券使用要求");
                }

                interest_new = interest_new.add(coupon.getInterestRate());

            }
        }
        //获取用户编号
        Long user_Id = resultUser.getId();
        //标的id
        Long projectId = Long.parseLong(project.getId());
        //0==1?
        BigDecimal awardValue = awardType == 1 ? redAmount : couponInterestRate;
        SUserBank banks = userBankMapper.selectUserBankByUserId(userId);
        if (banks == null || banks.getBankCardNo() == null || banks.getBankCardNo().equals("")) {
            return ObjectResult.build("0", "用户未绑定银行卡");
        }
        String bankCardNo = banks.getBankCardNo();

        //钱包余额判断
        SUserAccount sUserAccount = userAccountMapper.selectAccountAbleWaitInterestByUserId(resultUser.getId());
        if (sUserAccount.getAccount_able().compareTo(realMoney) < 0){
            return ObjectResult.build("0", "钱包余额不足,请充值");
        }


        String rechargeNo = p2PMessageUtils.getRechargeNo("B");
        String third_reserved = p2PMessageUtils.getRechargeNo("T");


        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("service", "bid_apply_p");
        reqMap.put("card_no",resultUser.getCard_no2());
        reqMap.put("out_serial_no",rechargeNo);
        reqMap.put("amount",amount.setScale(2).toString());
        reqMap.put("asset_no",project.getId());
        reqMap.put("interest_date",DateUtil.formatateTimeYYYYMMDD(DateUtil.addDateDay(project.getFrozenDate(),1)));
        reqMap.put("interest_type",project.getRepaymentType().toString());//付息方式 1：等额本息； 2：每月付息，到期还本
        if (project.getRepaymentType()==2){
//            String real_paydate = project.getReal_paydate();
//            String substring = real_paydate.substring(8, 10);
            reqMap.put("interest_day","20");
        }
        reqMap.put("end_date",DateUtil.formatateTimeYYYYMMDD(project.getRealPaydate()));
        reqMap.put("interest_rate",project.getUser_interest().setScale(5).toString());
        reqMap.put("frozen_flag","1");//是否冻结金额 0：不冻结； 1：冻结
        //使用红包
        if (awardType==1){
            reqMap.put("use_bonus","1");
            reqMap.put("bonus_amount",redAmount.setScale(2).toString());
        }else {
            reqMap.put("use_bonus","0");
            reqMap.put("bonus_amount","0.00");
        }
        reqMap.put("callback_url",PAGE_NOTIFY_URL+"tender/tenderNotify");
        reqMap.put("success_url",  CashInAndOutServiceImpl.PAGE_NOTIFY_URL+"index/resultHtml?type=1&title=7");
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("fail_url",  CashInAndOutServiceImpl.PAGE_NOTIFY_URL+"index/resultHtml?type=1&title=8");
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "MD5");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000001");
        reqMap.put("forget_pwd_url","http://apidata.rockfintech.com/doc/build/deposit.html");
        reqMap.put("client_ip", "47.98.107.188");
        reqMap.put("client_service", "00:16:3e:11:b0:02");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);

        System.out.println("reqMap:"+reqMap.toString());

        JSONObject jsonObject = JSONObject.parseObject(str);


        //添加投资记录
        ObjectResult saveRecordsResult = saveRecords(user_Id, projectId, rechargeNo, xmlBean, project.getNew_preferential(),
                awardType, awardId, amount, awardValue, rateCoupon, 1, bankCardNo,third_reserved,jsonObject.getString("sequence_id"),interest_new);
        if (saveRecordsResult != null) {
            return saveRecordsResult;
        }
        if(!jsonObject.getString("code").equals("RD000000")){
            return  ObjectResult.build("0",jsonObject.getString("msg"));
        }

        return ObjectResult.build("1", "成功",jsonObject.getString("url"));

    }


    //保存投资记录,投资前的记录
    public ObjectResult saveRecords(Long userId, Long projectId, String rechargeNo, XMLBean xmlBean, Integer projectType,
                                    Integer awardType, Integer awardId, BigDecimal amoney, BigDecimal awardValue, BigDecimal rateCoupon, Integer rechargeLogStatus, String bankCardNo,String third_reserved,String sequence_id,BigDecimal interest_new) {


        //保存投资充值记录
        ObjectResult insertRechargeLogResult = recordsUtils.insertRechargeLog(userId, projectId, rechargeNo, new BigDecimal(xmlBean.getMoney()), rechargeLogStatus, bankCardNo);
        if (insertRechargeLogResult != null) {
            return insertRechargeLogResult;
        }

        //保存详细投资记录
        ObjectResult insertInvestmentDetailResult = recordsUtils.insertInvestmentDetail(userId, projectId, rechargeNo, projectType,
                awardType, awardId, amoney, awardValue, rateCoupon,bankCardNo,third_reserved,sequence_id,interest_new);
        if (insertInvestmentDetailResult != null) {
            return insertInvestmentDetailResult;
        }
        //减去标的可投余额

        return null;
    }


    //投资回调报文验证,添加回调后校验成功的记录
    @Override
    public ObjectResult verificationTenderNotify(JSONObject jsonObject) {

        SInvestmentDetail SInvestmentDetail = investmentDetailMapper.selectsInvestmentetailByrechargeNo(jsonObject.getString("out_serial_no"));
        //返回数据验证
        if (SInvestmentDetail != null) {
            //如果使用了红包,减去红包的金额再比较
            BigDecimal invTotal1 = SInvestmentDetail.getInvTotal();
            Integer rewardType = SInvestmentDetail.getRewardType();
            rewardType = rewardType == null ? 0 : rewardType;

            if (new BigDecimal(jsonObject.getString("bid_amount")).compareTo(invTotal1) == 0) {

                //防止返回重复成功回调,重复添加记录
                if (SInvestmentDetail.getStatus() == 2) {
                    return ObjectResult.build("0", "投资已成功");
                }

                //查询
                SUser sUser = userMapper.selectUserInfoById(SInvestmentDetail.getUserId());
                XMLBean xmlBean = new XMLBean();
                xmlBean.setAmoney(SInvestmentDetail.getInvTotal().toString());
                xmlBean.setProject_id(String.valueOf(SInvestmentDetail.getProjectId()));
                SUser resultUser = userMapper.selectUserInfoById(SInvestmentDetail.getUserId());
                SProject project = projectMapper.selectProjectInfo(SInvestmentDetail.getProjectId());

                //保存成功投资记录并修改钱包余额
                ObjectResult objectResult1 = recordsUtils.saveInvestmentRecordsAndUpdateAccount(SInvestmentDetail.getUserId(), SInvestmentDetail.getProjectId(),jsonObject.getString("out_serial_no"), SInvestmentDetail.getInvTotal(),
                        SInvestmentDetail.getRewardId(), rewardType, SInvestmentDetail.getRewardValue(), SInvestmentDetail.getInterest_new(), 2, SInvestmentDetail.getBowType(), SInvestmentDetail.getCardNo(), 0, resultUser,jsonObject.getString("auth_code"));
                if (objectResult1 != null) {
                    return objectResult1;
                }

                //设置银行卡已支付
                SUserBank userBank = new SUserBank();
                userBank.setUserId(SInvestmentDetail.getUserId());
                userBank.setModifyTime(new Date());
                userBank.setHasPaySuccess(2);
                userBankMapper.updateByUserId(userBank);


                String pmsg = "尊敬的投资用户[" + resultUser.getRealName() + "]，您于" + DateUtil.formatDateTime() + "进行投的标[" + project.getTitle() + "]已经投标成功，冻结金额" + SInvestmentDetail.getInvTotal() + "元，请登录网站查看详情。【掌银金服】";
                //CommonUtils.sendPost(resultUser.getMobile(), pmsg);
                return ObjectResult.build("1", "投资成功");


            } else {
                return ObjectResult.build("0", "验签失败0x08");
            }

        } else {
            return ObjectResult.build("0", "不存在的投资记录");
        }

    }

    @Override
    public ObjectResult repayment(XMLBean xmlBean) {
        String userId =CommonUtils.decToken(xmlBean.getToken());
        SUser sUser = userMapper.selectByPrimaryKey(Long.parseLong(userId));

        SUserWalletRecords userWalletRecords = sUserWalletRecordsMapper.selectByPrimaryKey(Long.parseLong(xmlBean.getId()));
//        if (new Date().compareTo(userWalletRecords.getRepayment_time())<0){
//            ObjectResult.build("0","请勿提前还款");
//        }

        SUserAccount sUserAccount = userAccountMapper.selectByPrimaryKey(Long.parseLong(userId));

        if(userWalletRecords==null){
            return ObjectResult.build("0","错误的待还记录");
        }
//        if (sUserAccount.getAccount_able().setScale(2).compareTo(userWalletRecords.getValue().setScale(2))<0){
//            return ObjectResult.build("0","余额不足");
//        }
        SProjectWithBLOBs project = projectMapper.selectByPrimaryKey(Long.parseLong(userWalletRecords.getProject_id()+""));

        if(userWalletRecords.getUser_id()!=Long.parseLong(userId)&&project.getEnsure_user_id()!=Long.parseLong(userId)){
            return ObjectResult.build("0","非本标借款人或担保人");
        }

        Map<String,Object> data = new HashMap<>();
        data.put("count",userWalletRecords.getCount());
        data.put("projectId",userWalletRecords.getProject_id());
        data.put("payStatus",1);
        List<SUserWalletRecords> records = sUserWalletRecordsMapper.selectByMap(data);

        List<Map<String,Object>> list = new ArrayList<>();

        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        String rechargeNo = p2PMessageUtils.getRechargeNo("RE");//订单号

        if (records==null || records.size()<1){
            return ObjectResult.build("0","无未还款投资");
        }

        //借款人还款
        BigDecimal amount = new BigDecimal(0);

        for (SUserWalletRecords sUserWalletRecords:records){
            SUserDueDetail sUserDueDetail = sUserDueDetailMapper.selectUserDueDetailLastByProjectId(sUserWalletRecords.getUser_due_detail_id().toString());

            Map<String,Object> map = new HashMap<>();
            map.put("out_card_no",sUser.getCard_no2());//扣款账号
            map.put("in_card_no", userMapper.selectByPrimaryKey(sUserWalletRecords.getUser_id()).getCard_no2());//转入账号
            //最后一次连同本金一起还
            if(project.getSurplus_repayment_count()==1){
                map.put("amount",sUserDueDetail.getDue_capital().setScale(2).toString());//本金
                map.put("interest_amount",sUserWalletRecords.getValue().subtract(sUserDueDetail.getDue_capital()).setScale(2).toString());//利息
                map.put("end_flag","1");//结束标识位，1：结束 0：未结束
            }
            else {
                map.put("end_flag","0");//结束标识位，1：结束 0：未结束
                map.put("interest_amount",sUserWalletRecords.getValue().setScale(2).toString());//利息
            }
            String h = p2PMessageUtils.getRechargeNo("H");

            map.put("currency","156");//币种 156人民币
            map.put("out_fee_mode","0");//转出方手续费扣款方式 0 指定金额
            map.put("out_fee_amount","0.00");//转出方手续费扣款金额
            map.put("in_fee_mode","0");//转入方手续费扣款方式 0 指定金额
            map.put("in_fee_amount","0.00");//转入方手续费扣款金额
            map.put("assets_no",project.getId());//标的编号
            map.put("auth_code",sUserDueDetail.getAuth_code());//投标申请授权码
            map.put("third_reserved",h);//第三方流水号
            map.put("serial_no",sUserDueDetail.getRecharge_no());//投标申请流水号
            list.add(map);
            amount = amount.add(sUserWalletRecords.getValue());

            //添加订单号
            sUserWalletRecords.setRecharge_no(h);
            sUserWalletRecordsMapper.updateByPrimaryKeySelective(sUserWalletRecords);
        }


        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("service","batch_repayment_b");
        reqMap.put("batch_no",rechargeNo);
        reqMap.put("batch_count",list.size()+"");
        reqMap.put("batch_type","002");
        reqMap.put("batch_date",DateUtil.formatateTimeYYYYMMDD());
        reqMap.put("items", JSONArray.fromObject(list));
        reqMap.put("notify_url",CashInAndOutServiceImpl.PAGE_NOTIFY_URL+"project/repaymentNotify");
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000001");
        reqMap.put("client_ip", "47.98.107.188");
        reqMap.put("client_service", "00:16:3e:11:b0:02");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);
        System.out.println(str.toString());
        JSONObject jsonObject = JSONObject.parseObject(str);

        if(!jsonObject.getString("code").equals("RD000000")){
            return  ObjectResult.build("0",jsonObject.getString("msg"));
        }

        //修改借款人还款记录
        userWalletRecords.setSequence_id(jsonObject.getString("sequence_id"));
        userWalletRecords.setPayStatus(3);
        userWalletRecords.setRecharge_no(rechargeNo);
        sUserWalletRecordsMapper.updateByPrimaryKeySelective(userWalletRecords);

        return ObjectResult.build("1","还款申请成功");
    }




    @Override
    public List<SProject> selectProjectList() {
        return projectMapper.selectProjectList();
    }

    public ObjectResult loanNotify(List<Map<String, String>> list,String batch_no) {

        SUserWalletRecords sUserWalletRecords = sUserWalletRecordsMapper.selectWalletRecordsByrRechargeNo(batch_no);

        if(sUserWalletRecords==null){
            LOGGER.info("查询不到借款人还款记录");
            return ObjectResult.build("0","查询不到借款人还款记录");
        }
        if(sUserWalletRecords.getPayStatus()==2){
            LOGGER.info("重复的回调");
            return ObjectResult.build("1","重复的回调");
        }

        if (list.size()<1){
            LOGGER.info("list为空");
            return ObjectResult.build("0","list为空");
        }

        SProjectWithBLOBs sProject = projectMapper.selectByPrimaryKey((Long.parseLong(sUserWalletRecords.getProject_id() + "")));
        Map<String, Object> resultMap = new HashMap<>();

        for (Map<String, String> map:list){

            if(!map.get("result").equals("00")){
                LOGGER.info("------------------------- "+map.get("serial_no")+" | "+map.get("message")+" ----------------------------");
                continue;
            }

            SUserDueDetail detail = sUserDueDetailMapper.selectUserDueDetailByRechargeno(map.get("serial_no"));
            if(detail==null){
                LOGGER.info("------------------------- "+map.get("serial_no")+" | 已还款  ----------------------------");
                continue;
            }

            //修改还款记录状态
            SUserWalletRecords walletRecords = sUserWalletRecordsMapper.selectWalletRecordsByrRechargeNo(map.get("third_reserved"));
            walletRecords.setPayStatus(2);
            sUserWalletRecordsMapper.updateByPrimaryKeySelective(walletRecords);

            BigDecimal due_capital = new BigDecimal(0);//本金
            BigDecimal due_interest = new BigDecimal(0);//利息

            //最后一次还款修改投资记录状态
            if (sProject.getSurplus_repayment_count()==1) {
                detail.setStatus(2);
                detail.setStatusNew(2);
                detail.setModifyTime(new Date());
                sUserDueDetailMapper.updateByPrimaryKeySelective(detail);

                SInvestmentDetail investmentDetail = investmentDetailMapper.selectsInvestmentetailByrechargeNo(map.get("serial_no"));
                investmentDetail.setStatus(4);
                investmentDetail.setStatusNew(4);
                investmentDetail.setModifyTime(new Date());
                investmentDetail.setThird_reserved(walletRecords.getRecharge_no());
                investmentDetailMapper.updateByPrimaryKeySelective(investmentDetail);
                due_capital = detail.getDue_capital();
                due_interest = walletRecords.getValue().subtract(due_capital);
            }else {
                due_interest = walletRecords.getValue();
            }


            SUserAccount account = userAccountMapper.selectUserAccountByUserId(detail.getUserId());

            //转入投资人余额
            account.setWalletTotle(account.getWalletTotle().add(due_capital).add(due_interest));//钱包总金额
            account.setTotalInvestCapital(account.getTotalInvestCapital().add(due_capital));//总的已还款本金
            account.setTotalInvestInterest(account.getTotalInvestInterest().add(due_interest));//总的已还投资收益
            account.setAccount_total(account.getAccount_total().subtract(due_capital).subtract(due_interest));
            account.setAccount_able(account.getAccount_able().add(due_capital).add(due_interest));//可用金额
            account.setWait_amount(account.getWait_amount().subtract(due_capital).subtract(due_interest));//待收总金额
            account.setWaitCapital(account.getWaitCapital().subtract(due_capital));//待收总本金
            account.setWait_interest(account.getWait_interest().subtract(due_interest));//待收总利息
            account.setWalletProductInterest(account.getWalletProductInterest().add(due_interest));//由钱包投资产品所得利息
            userAccountMapper.updateByPrimaryKeySelective(account);


            //扣除借款人人余额
            SUserAccount account2 = userAccountMapper.selectUserAccountByUserId(sUserWalletRecords.getUser_id());
            account2.setWalletTotle(account2.getWalletTotle().subtract(due_capital).subtract(due_interest));//钱包总金额
            account2.setAccount_able(account2.getAccount_able().subtract(due_capital).subtract(due_interest));//可用金额
            account2.setWait_amount(account2.getWait_amount().subtract(due_capital).subtract(due_interest));//待收总金额
            account2.setWaitCapital(account2.getWaitCapital().subtract(due_capital));//待收总本金
            account2.setWait_interest(account2.getWait_interest().subtract(due_interest));//待收总利息
            userAccountMapper.updateByPrimaryKeySelective(account2);

        }

        Map<String,Object> data = new HashMap<>();
        data.put("count",sUserWalletRecords.getCount());
        data.put("projectId",sUserWalletRecords.getProject_id());
        data.put("payStatus",1);
        List<SUserWalletRecords> records = sUserWalletRecordsMapper.selectByMap(data);



        if (records==null || records.size()<1) {
            //修改借款人还款记录状态
            sUserWalletRecords.setPayStatus(2);
            sUserWalletRecords.setReal_time(new Date());
            sUserWalletRecordsMapper.updateByPrimaryKeySelective(sUserWalletRecords);

            //修改标的待还次数
            //如果为最后一次还款修改标的状态为已还款
            if (sProject.getSurplus_repayment_count() == 1) {
                sProject.setSurplus_repayment_count(0);
                sProject.setStatus(5);
            } else {
                sProject.setSurplus_repayment_count(sProject.getSurplus_repayment_count() - 1);
            }
            projectMapper.updateByPrimaryKeySelective(sProject);

            //修改还款表状态为成功
            List<SRepaymentDetail> repaymentDetails = repaymentDetailMapper.selectByProjectId(sUserWalletRecords.getProject_id());
            SRepaymentDetail sRepaymentDetail = repaymentDetails.get(0);
            if (sRepaymentDetail != null) {
                sRepaymentDetail.setStatusNew(2);
                sRepaymentDetail.setStatus(2);
                sRepaymentDetail.setModifyTime(new Date());
                repaymentDetailMapper.updateByPrimaryKeySelective(sRepaymentDetail);
            }

            LOGGER.info("-----------------------还款成功-----------------------");

            return ObjectResult.build("1", "还款成功");
        }else {
            LOGGER.info("---------------------存在未成功还款--------------------");
            sUserWalletRecords.setPayStatus(1);
            sUserWalletRecordsMapper.updateByPrimaryKeySelective(sUserWalletRecords);
            return ObjectResult.build("1", "存在未成功还款");
        }

    }

    @Override
    public ObjectResult batchRevokeRepayment(XMLBean xmlBean) {
        String userId ="39";//CommonUtils.decToken(xmlBean.getToken());
        SUser sUser = userMapper.selectByPrimaryKey(Long.parseLong(userId));

        SUserWalletRecords userWalletRecords = sUserWalletRecordsMapper.selectByPrimaryKey(Long.parseLong(xmlBean.getId()));

        SProjectWithBLOBs project = projectMapper.selectByPrimaryKey(Long.parseLong(userWalletRecords.getProject_id().toString()));


        Map<String,Object> data = new HashMap<>();
        data.put("count",userWalletRecords.getCount());
        data.put("projectId",userWalletRecords.getProject_id());
        data.put("payStatus",1);
        List<SUserWalletRecords> records = sUserWalletRecordsMapper.selectByMap(data);

        List<Map<String,Object>> list = new ArrayList<>();

        for (SUserWalletRecords sUserWalletRecords:records){
            SUserDueDetail sUserDueDetail = sUserDueDetailMapper.selectUserDueDetailLastByProjectId(sUserWalletRecords.getUser_due_detail_id().toString());

            Map<String,Object> map = new HashMap<>();
            map.put("out_card_no",sUser.getCard_no2());//扣款账号
            map.put("in_card_no", userMapper.selectByPrimaryKey(sUserWalletRecords.getUser_id()).getCard_no2());//转入账号
            map.put("assets_no",project.getId());//标的编号
            map.put("auth_code",sUserDueDetail.getAuth_code());//投标申请授权码
            map.put("third_reserved",sUserWalletRecords.getRecharge_no());//第三方流水号
            map.put("serial_no",sUserDueDetail.getRecharge_no());//投标申请流水号
            list.add(map);
        }

        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("service","batch_revoke_payment_b");
        reqMap.put("batch_no",userWalletRecords.getRecharge_no());
        reqMap.put("batch_count",list.size()+"");
        reqMap.put("batch_type","002");
        reqMap.put("batch_date",DateUtil.formatateTimeYYYYMMDD());
        reqMap.put("items", JSONArray.fromObject(list));
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000001");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);
        System.out.println(str.toString());
        JSONObject jsonObject = JSONObject.parseObject(str);

        if(!jsonObject.getString("code").equals("RD000000")){
            return  ObjectResult.build("0",jsonObject.getString("msg"),jsonObject);
        }

        return ObjectResult.build("1","还款撤销成功");
    }


    @Override
    public SProject selectProjectByPid(String id) {
        return projectMapper.selectProjectByPid(id);
    }

    @Override
    public List<SProject> selectProjectInvestList(String pid) {
        return projectMapper.selectProjectInvestList(pid);
    }

    @Override
    public List<SProject> selectUserInvestList(Map<String, Object> map) {
        return projectMapper.selectUserInvestList(map);
    }

    @Override
    public SProject selectProjectListLevel1() {
        return projectMapper.selectProjectListLevel1();
    }

    @Override
    public SProject selectProjectListLevel2() {
        return projectMapper.selectProjectListLevel2();
    }

    @Override
    public ObjectResult rank(XMLBean xmlBean) {
        Map<String,Map<String,Object>> map = new HashMap<>();
        Map<String,Object> map2 = new HashMap<>();
        SUser sUser = null;
        if(xmlBean.getToken()!=null){
            sUser = userMapper.selectByPrimaryKey(Long.parseLong(CommonUtils.decToken(xmlBean.getToken())));
        }

        List<SUserDueDetail> list = sUserDueDetailMapper.selectRank();
        int count = 1;//排名
        for (SUserDueDetail sUserDueDetail:list){
            Map<String,Object> data = new HashMap<>();
            data.put("rank",count);
            data.put("amount",sUserDueDetail.getDue_capital());
            count++;
            map.put(sUserDueDetail.getMobile(),data);
        }

        Page<SUserDueDetail> page = new Page<>();
        page.setP(1);
        page.setPageSize(10);
        List<SUserDueDetail> content = page.getPageContent(list);
        count =1;
        for (SUserDueDetail sUserDueDetail:content){
            sUserDueDetail.setRank(count);
            sUserDueDetail.setMobile(CommonUtils.concealMobile(sUserDueDetail.getMobile()));
            count++;
        }
        map2.put("list",content);
        Map<String, Object> pram = new HashMap<>();

        if (sUser==null || map.get(sUser.getMobile())==null){//未投资或未登录没有排名
            pram.put("rank",0);
            pram.put("amount",new BigDecimal(0));
            map2.put("user",pram);
        }else {
            map2.put("user",map.get(sUser.getMobile()));
        }
        return ObjectResult.build("1","成功",map2);
    }

    @Override
    public ObjectResult borrowerFunds(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser sUser = userMapper.selectByPrimaryKey(Long.parseLong(userId));
        if (sUser.getType()!=2&&sUser.getType()!=3){
            return ObjectResult.build("0","非借款人或担保人");
        }

//        if(sUser.getType()==3){
//            List<String> userIdList = projectMapper.selectLoanUseridByEnsureUserId(userId);
//            List<SUserWalletRecords> list = new ArrayList<>();//全部担保的待还list
//            if (userIdList.size()>0){
//                for (String userid:userIdList){
//                    Map<String,Object> data = new HashMap<>();
//                    data.put("userId",userid);
//                    data.put("payStatus",xmlBean.getPayStatus());
//                    data.put("type",xmlBean.getType());
//                    List<SUserWalletRecords> sUserWalletRecords = sUserWalletRecordsMapper.selectRepaymentAndLoanByMap(data);//还款列表
//                    list.addAll(sUserWalletRecords);
//                }
//
//                //                    Page<SUserWalletRecords> page = new Page<>();
////                    page.setP(xmlBean.getP()==null? 1:xmlBean.getP());
////                    page.setPageSize(10);
////                    List<SUserWalletRecords> content = page.getPageContent(sUserWalletRecords);
//            }
//        }
//        else {
            Map<String,Object> data = new HashMap<>();
            data.put("userId",userId);
            data.put("payStatus",xmlBean.getPayStatus());
            data.put("type",xmlBean.getType());
            data.put("userType",sUser.getType());
            List<SUserWalletRecords> sUserWalletRecords = sUserWalletRecordsMapper.selectRepaymentAndLoanByMap(data);//还款列表
            Page<SUserWalletRecords> page = new Page<>();
            page.setP(xmlBean.getP()==null? 1:xmlBean.getP());
            page.setPageSize(10);
            List<SUserWalletRecords> content = page.getPageContent(sUserWalletRecords);

            BigDecimal waitRepay = sUserWalletRecordsMapper.selectRepay(data)==null? new BigDecimal(0):sUserWalletRecordsMapper.selectRepay(data);//应还总额
            data.put("time",new Date());
            BigDecimal nowRepay =sUserWalletRecordsMapper.selectRepay(data)==null? new BigDecimal(0):sUserWalletRecordsMapper.selectRepay(data);//当前应还
            BigDecimal loanAmount = projectMapper.selectLoanAmount(userId)==null? new BigDecimal(0):projectMapper.selectLoanAmount(userId);//借款金额

            Map<String,Object> map = new HashMap<>();
            map.put("nowRepay",nowRepay);
            map.put("waitRepay",waitRepay);
            map.put("loanAmount",loanAmount);

            for (SUserWalletRecords userWalletRecords:content){
                if (userWalletRecords.getType()==3){
                    userWalletRecords.setReal_time(userWalletRecords.getAdd_time());
                }

//            SUserDueDetail sUserDueDetail = sUserDueDetailMapper.selectDueAmountByProjectId(sProject.getId());
//
//            LOGGER.info(sUserDueDetail.getDue_capital()+" "+sUserDueDetail.getDue_interest()+" "+sProject.getId());
//            if(sUserDueDetail.getDue_capital()==null){
//                sProject.setInterest(new BigDecimal(0));
//                sProject.setAmount(new BigDecimal(0));
//            }else {
//                sUserDueDetail.setDue_interest(sUserDueDetail.getDue_interest()==null? new BigDecimal(0):sUserDueDetail.getDue_interest());
//                sProject.setInterest(sUserDueDetail.getDue_interest());//利息
//                sProject.setAmount(sUserDueDetail.getDue_capital());//借款金额
//            }

            }
            map.put("list",content);
            map.put("count",page.getPageTotal());
            return ObjectResult.build("1","成功",map);
//        }

    }


    /**
     * 放还款签约余额查询
     * @param card_no
     * @param service
     * @return
     */
    public String selectRemainingAmount(String card_no,String service){
        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("service", service);
        reqMap.put("card_no", card_no);
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000001");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);
        JSONObject jsonObject = JSONObject.parseObject(str);
        return jsonObject.getString("remaining_amount");
    }

}

